/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable prefer-const */

/**
 * 参数过滤
 * @param obj json 参数
 * @return 过滤掉为空的参数
 * @author: herther
 * @since 1.0.0
 * @date: 2022/9/12 14:38
 */
const removeEmpty = (obj: object): object => {
  Object.keys(obj).forEach((k: string, value: any) => {
    /* eslint-disable no-param-reassign */
    value = obj[k];
    if (value === '') delete obj[k];
    else if (value.constructor == Object) removeEmpty(value);
  });
  return obj;
};

/**
 * 构建分页参数
 * @param {查询参数} queryParams
 * @param {排序参数} sorts
 */
const buildParams = (queryParams: any, sorts: string) => {
  queryParams.page = queryParams.current;
  delete queryParams.current;
  queryParams.sorted = buildSorted(sorts);
  // 移除空的参数
  removeEmpty(queryParams);
  return queryParams;
};

/**
 * 构建排序
 */
const buildSorted: any = (sorts: any): any => {
  let sortStr = '';
  Object.keys(sorts).forEach((k: string, v: any) => {
    v = sorts[k];
    let tempRule;
    if (v.indexOf('desc') == 0) {
      tempRule = 'desc';
    } else {
      tempRule = 'asc';
    }
    sortStr = k + ':' + tempRule;
  });
  return sortStr;
};

const copyObj = (obj: any) => {
  const res: any = {};
  for (const key in obj) {
    res[key] = obj[key];
  }
  return res;
};

export { removeEmpty, buildParams, buildSorted, copyObj };
